package com.sys;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.StrictMode;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.MemoryCacheAware;
import com.nostra13.universalimageloader.cache.memory.impl.LRULimitedMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.umeng.message.UmengRegistrar;
import com.util.Constant;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;

public class DemoApp extends Application {
	static private Context mContext;
	private List<Activity> activities = new ArrayList<Activity>();
	
	public JSONArray mBabyList = null;
	public int mSelectedBaby = 0;
	public int glbUnit = 2;
	public boolean isNewMsg = false;
	
	@SuppressLint("NewApi")
	@Override
	public void onCreate() {
		super.onCreate();

		mContext = getApplicationContext();

		if (Constants.DEBUG_MODE
				&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
					.detectDiskReads().detectDiskWrites().detectNetwork() // or
																			// .detectAll()
																			// for
																			// all
																			// detectable
																			// problems
					.penaltyLog().build());
			StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
					.detectLeakedSqlLiteObjects().penaltyLog().build());
		}

		if (!Constants.DEBUG_MODE) {
			MyUncaughtExceptionHandler exceptionHandler = MyUncaughtExceptionHandler
					.getExceptionHandler(getApplicationContext());
			Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);
		}

		initImageLoader(getApplicationContext());
	}
	
	public void sendGetBabyRequest(Context context) {
		MgqDataHandler loginHandler = new MgqDataHandler(context, true, false) {
			@Override
			public void onSuccess(String response) {
				((DemoApp)getApplicationContext()).mBabyList = JSON.parseArray(response);
				if(((DemoApp)getApplicationContext()).mBabyList != null)
				{
					int count = ((DemoApp)getApplicationContext()).mBabyList.size();
					for(int i = 0; i < count; i++)
					{
						JSONObject item = ((DemoApp)getApplicationContext()).mBabyList.getJSONObject(i);
						if(item.getString("isCurr").equals("true")) ((DemoApp)getApplicationContext()).mSelectedBaby = i;
					}
				}
			}
		};
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		params.put("handType", "get");

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/babyInfoHandler.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	public void sendLoginRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, false, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("resCode").equals("1000")) {
					PreferencesUtils.putString(getApplicationContext(), "nickname", ruser.getString("nickname"));
					PreferencesUtils.putString(getApplicationContext(), "userimg", ruser.getString("userimg"));
					PreferencesUtils.putString(getApplicationContext(), "accessToken", ruser.getString("accessToken"));
				}
			}
		};
		
		JSONObject params = new JSONObject();
		params.put("userName", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		params.put("tid", "");
		params.put("deviceid", UmengRegistrar.getRegistrationId(this));

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/login.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	public JSONObject getSeletedBaby()
	{
		if(mBabyList != null) return mBabyList.getJSONObject(mSelectedBaby);
		return null;
	}

	public void addActivity(Activity activity) {
		activities.add(activity);
	}

	public void removeActivity(Activity activity) {
		activities.remove(activity);
	}

	public List<Activity> getActivityList() {
		return activities;
	}

	@Override
	public void onTerminate() {

		super.onTerminate();
		exit();
	}

	public void exit() {
		for (Activity activity : activities) {
			activity.finish();
		}
		System.exit(0);
	}

	public int getActivitySize() {
		return activities.size();
	}

	public static boolean isIntentAvailable(Context context, Intent intent) {
		final PackageManager packageManager = context.getPackageManager();
		List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
				PackageManager.GET_ACTIVITIES);
		return list.size() > 0;
	}

	public static void initImageLoader(Context context) {
		int memoryCacheSize = (int) (Runtime.getRuntime().maxMemory() / 3);

		MemoryCacheAware<String, Bitmap> memoryCache;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
			memoryCache = new LruMemoryCache(memoryCacheSize);
		} else {
			memoryCache = new LRULimitedMemoryCache(memoryCacheSize);
		}

		// This configuration tuning is custom. You can tune every option, you
		// may tune some of them,
		// or you can create default configuration by
		// ImageLoaderConfiguration.createDefault(this);
		// method.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context).threadPriority(Thread.NORM_PRIORITY - 2)
				.memoryCache(memoryCache).denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.FIFO).build();
		// .tasksProcessingOrder(QueueProcessingType.LIFO).build();

		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
		// com.nostra13.universalimageloader.utils.L.setLogEnable(false);
	}
	
	static public Context getContext()
	{
		return mContext;
	}
}
